//login 和 register
const express = require("express")
const router=express.Router()
const md5 = require("md5")
const {comMysql}=require("../../mysql")
const {secretOrKey}=require("../../mysql")
const gravatar = require("gravatar")
var jwt = require('jsonwebtoken');
const passport = require("passport")
const url=require("url")

//GET请求 api/users/test
//@desc 返回请求的JSON数据
//@access public 
// router.get("/test",(req,res)=>{
//   res.json({msg:"login"})
// })

router.post("/register",async (req,res)=>{
  let {email,name,password,date,avatar,identity}=req.body
  // 查询数据库中是否拥有邮箱
  let sql="select * from users where email = ?"
  let arr=[email]
  const data = await comMysql(sql,arr)
  
  if(data.length>0){
    res.status(400)
  }else{
    if(!avatar){
      avatar = gravatar.url(email, {s: '200', r: 'pg', d: 'mm'});
    }
    let salt="zxh";
    password=md5(password+salt).substring(0,9)
    let sql1=`insert into users(name,email,password,avatar,date,identity) values (?,?,?,?,?,?)`
    let arr1=[name,email,password,avatar,date,identity]
    const result = await comMysql(sql1,arr1)
    let fin={email,name,password,date,avatar,identity}
    res.json({success:fin})
  }
  
})
//login
//返回json token jwt password
router.post("/login",async (req,res)=>{
  let {email,password} = req.body
  let sql=`select * from users where email = ? and password = ?`
  let arr=[email,password]
  const data=await comMysql(sql,arr)
  if(data.length<0){
    res.status(404)
  }
  let salt="zxh"
  password=md5(password+salt).substring(0,9)
  if(password!=data[0].password){
    return res.status(404).json({msg:"用户名或密码错误"})
  }else{
    //将id name avatar identity 添加到token中
    const rule={id:data[0].id,name:data[0].name,avatar:data[0].avatar,identity:data[0].identity}
    console.log(rule);
    
    //expiresIn XX秒
    jwt.sign(rule,secretOrKey,{expiresIn:3600*24},(err,token)=>{
      if(err){
        throw err;
      }else{
        res.json({
          success:true,
          token:"Bearer "+token
        })
      }
      
    })
  }
})

//get current
router.get("/current",passport.authenticate("jwt",{session:false}),(req,res)=>{
  res.json(req.user)
  
})
//get 更换头像
router.get("/avatar",async (req,res)=>{
  let sql=`update users set avatar=? where id = ?`
  let avatar = url.parse(req.url,true).query
  let arr=[avatar.avatar,avatar.id]
  const data = await comMysql(sql,arr)
  console.log(data);
  
  if(data.changedRows>0){
    res.send("成功")
  }
}
)

module.exports=router